package org.suanfaTranning.ST200_Chatpter1_LineTable_HashTable_String.array;

/**
 * @Auther: qingle
 * @Date: 2024/9/11-17:11
 * @Description:
 * @version: 1.0
 */
public class Solution_lengthOfLongestSubstring4 {
	public static int lengthOfLongestSubstring(String s) {
		int res = 0; // 最长子串的计算结果
		int left = 0; // 子串起始索引
		int right = 0; // 子串结束索引
		int len = s.length(); // 字符串长度
		// 1.哈希表中填充ASCII码表不包含的数值作为默认值：-1
		int[] arr = new int[128];
		for (int i = 0; i < arr.length; i++)
			arr[i] = -1;
		// 2.遍历字符串的所有字符
		while (right < len) {
			int c = s.charAt(right);
			if (arr[c] != -1) { // 检测该字符是否已出现：已出现
				// 出现，则移动左指针，直接定位到上次出现的下一个索引
				int start0 = arr[c] + 1;
				// 2.1.使用双指针定位子串索引：左指针直接定位
				left = left >= start0 ? left : start0; // 只往右不往左
			}
			arr[c] = right; // 无论是否重复，记录该字符最后一次出现的索引
			// 3.计算子串长度，记录最大值：右索引+1 - 左索引
			int size = right + 1 - left;
			res = res > size ? res : size;
			// 2.2.使用双指针定位子串索引：右指针始终自增
			right++;
		}
		return res;
	}

		public static void main(String[] args) {
			Solution_lengthOfLongestSubstring4 solution = new Solution_lengthOfLongestSubstring4();
			String input1 = "abcabcbb";
			System.out.println("Input: \"" + input1 + "\", Output: " + Solution_lengthOfLongestSubstring4.lengthOfLongestSubstring(input1));

			String input2 = "bbbbb";
			System.out.println("Input: \"" + input2 + "\", Output: " + Solution_lengthOfLongestSubstring4.lengthOfLongestSubstring(input2));

			String input3 = "pwwkew";
			System.out.println("Input: \"" + input3 + "\", Output: " + Solution_lengthOfLongestSubstring4.lengthOfLongestSubstring(input3));
		}
	}